package com.unicom.office.templatefunc;

import com.unicom.office.dataitem.*;
import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.type.NumberTypeItem;
import com.unicom.office.type.TypeItem;
import com.unicom.office.unit.OfficeUnit;
import com.unicom.office.var.ObjectVarItem;

import java.util.List;
import java.util.Map;

public class ItemFunc extends TemplateFunc {
    public static final ItemFunc INSTANCE = new ItemFunc();

    private ItemFunc(){}

    public Object run(List<Object> params, OfficeRuntime officeRuntime) {
        ListDataItem list = (ListDataItem) params.get(0);

        if(params.size() == 2) {
            Integer index = ((NumberDataItem) params.get(1)).getIntValue();
            if(index >= list.getValue().size()) {
                return new RuntimeException("数组index越界");
            }
            return new ObjectDataItem(list.getValue().get(index), (ObjectVarItem) list.getConfig().getItemType().createVarItem("item"));
        }else if(params.size() == 3) {
            StringDataItem key = (StringDataItem) params.get(1);
            StringDataItem value = (StringDataItem) params.get(2);

            for (Object item : list.getValue()) {
                Map<String, Object> map = (Map<String, Object>) item;
                if(map.containsKey(key.getValue())) {
                    if(map.get(key.getValue()).equals(value.getValue())) {
                        return new ObjectDataItem(map, (ObjectVarItem) list.getConfig().getItemType().createVarItem("item"));
                    }
                }
            }
            throw new RuntimeException("数据未找到");
        }

        Double num = 0d;
        for (Object param : params) {
            NumberDataItem temp = (NumberDataItem) param;
            num += temp.getDoubleValue();
        }
        return NumberDataItem.create(num);
    }

    public void runForMatch(OfficeUnit unit, List<Object> params, OfficeRuntime officeRuntime) {

    }

    public String getName() {
        return "item";
    }

    public TypeItem getType() {
        return NumberTypeItem.INSTANCE;
    }
}
